<template>
  <div>
    <slot
      name="input"
      :value-text="valueText"
      :show-picker="showPicker"
    >
      <van-field
        class="buildPageInput"
        :value="valueText"
        :label="label"
        placeholder=""
        readonly
        :rules="rules"
        :is-link="!disabled"
        @click="showPicker"
        :required="required"
        :disabled="disabled"
      />
    </slot>
    <van-popup
      v-model="picker.show"
      position="bottom"
      get-container="body"
    >
      <van-picker
        v-if="multiple === false"
        :title="pickerTitle"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        :value-key="labelKey"
        @change="onChange"
      />
      <van-tree-select
        v-else
        :items="columns"
        :max="max"
        :active-id.sync="treeSelect.value"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'CommonPicker',
  props: {
    label: {
      type: String,
      default: ''
    },
    value: {
      type: Array,
      default () {
        return []
      } },
    disabled: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    pickerTitle: {
      type: String,
      default: ''
    },
    rules: {
      type: Array,
      default () {
        return []
      }
    },
    // 多选时columns结构参考 https://vant-contrib.gitee.io/vant/v2/#/zh-CN/tree-select#item-shu-ju-jie-gou
    multiple: {
      type: Boolean,
      default: false
    },
    max: {
      type: Number,
      default: 100
    },
    // labelKey valueKey 在多选时不支持，统一文字text，值id
    labelKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    required: {
      type: Boolean,
      default: false
    },
    // 多选时选择项结果是否加上父级的文字 (childText, childText) (parentText/childText, parentText/childText)
    showParentText: {
      type: Boolean,
      default: false
    },
    // 非树结构数据多选
    flatMultiple: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      picker: {
        show: false
      },
      treeSelect: {
        value: []
      }
    }
  },
  watch: {
    'picker.show': {
      handler (newVal) {
        if (this.multiple) {
          if (newVal) {
            this.treeSelect.value = [...this.value]
          } else {
            this.$emit('input', this.treeSelect.value)
            this.$emit('confirm', this.treeSelect.value)
          }
        }
      },
      immediate: false
    }
  },
  computed: {
    valueText () {
      if (this.flatMultiple) {
        let arr = []
        this.columns.forEach(col => {
          arr.push(col.text)
        })
        return arr.join(',')
      }
      if (this.multiple) {
        const r = []
        const b = new Map()
        this.columns.forEach(col => {
          if (col.children) {
            col.children.forEach(child => {
              const value = this.value.find(o => o === child.id)
              if (!b.has(child.id) && value) {
                b.set(child.id, '')
                r.push(this.multipleTextFormatter(child, col))
              }
            })
          }
        })
        console.log(r.join(','), 'r.join(', ')');
        return r.join(',')
      } else {
        const option = this.columns.find(item => item[this.valueKey] === this.value)
        if (option) {
          return option[this.labelKey]
        } else {
          switch (typeof this.value) {
            case 'string':
              return this.value
            case 'undefined':
              return ''
            case 'object':
              return ''
              // return JSON.stringify(this.value)
            default:
              return String(this.value)
          }
        }
      }
    }
  },
  methods: {
    onConfirm (value, index) {
      const diff = value[this.valueKey] !== this.value
      this.$emit('input', value[this.valueKey])
      this.$emit('confirm', value, index)
      if (diff) {
        this.$emit('change', value, index)
      }
      this.picker.show = false
    },
    onCancel () {
      this.picker.show = false
    },
    onChange () {

    },
    showPicker () {
      if (!this.disabled) {
        this.picker.show = true
      }
    },
    multipleTextFormatter (child, parent) {
      return this.showParentText ? `${parent.text}/${child.text}` : child.text
    }
  },
  filters: {
    optionFilter (value, columns) {
      const option = columns.find(item => item.value === value)
      if (option) {
        return option[this.labelKey]
      } else {
        return value
      }
    }
  }
}
</script>

<style scoped>

</style>
